package com.tanhua.admin.interceptor;

import com.tanhua.admin.pojo.AdminUser;
import com.tanhua.admin.service.SystemService;
import com.tanhua.admin.utils.AdminUserThreadLocal;
import com.tanhua.admin.utils.NoAuthorization;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: JinboYang
 * @Description: 统一根据token去查询user
 * @Date: Created in 下午 14:19 2021/1/7
 * @ModifiedBy:
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private SystemService systemService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            // 查看Controller上有没有NoAuthorization这个注解,如果有 表示无需验证权限即可访问,直接返回true通过
            NoAuthorization noAuthorization = handlerMethod.getMethod().getAnnotation(NoAuthorization.class);
            if (noAuthorization != null) {
                // 如果该方法被标记为无需验证token,直接返回即可
                return true;
            }
        }

        String token = request.getHeader("Authorization");
        if (StringUtils.isNotEmpty(token)) {
            if (token.startsWith("Bearer ")) {
                token = token.replace("Bearer ", "");
            }
            AdminUser adminUser = systemService.queryUserByToken(token);

            if (null != adminUser) {
                AdminUserThreadLocal.set(adminUser);  // 将当前对象存储到当前的线程中
                return true;
            }
        }

        // 因为上面筛选了 包含 @NoAuthorization 的请求,所以这里筛选的都是要有权限验证的接口
        response.setStatus(401); // 因为前面筛选了能找到token的情况,所以这里执行的是既没有 @NoAuthorization 也没有token 的情况
        return false;
    }
}
